package com.tian.user.exception;

import com.alibaba.fastjson.JSONObject;
import com.tian.common.result.BaseResult;
import com.tian.common.result.Result;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.oauth2.common.exceptions.InvalidTokenException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 *
 * <pre>
 *     全局请求头校验
 *     get方法，请把access_token 直接拼在请求地址后面 例如 http://www.baidu.com?access_token=xxxx
 * </pre>
 * @author zhumengping
 * @title: AuthExceptionEntryPoint
 * @projectName zhump-cloud
 * @date 2023/8/4 17:09
 */
@Component
public class AuthenticationEntryPointException implements AuthenticationEntryPoint {



    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) {
        Throwable cause = authException.getCause();
        response.setStatus(HttpStatus.OK.value());
        response.setHeader("Content-Type","application/json;charset=UTF-8");
        BaseResult<Object> wrap = null;
        try {
            if (cause instanceof InvalidTokenException){
                wrap = Result.wrap(-1, "认证失败,无效token");
            }else {
                wrap = Result.wrap(-1,"认证失败，没有携带token");
            }
            response.getWriter().write(JSONObject.toJSONString(wrap));
        }catch (IOException e){
            e.printStackTrace();
        }

    }
}
